/**
*	oa审批事项列表查询页面
*
*/

define(['jquery','init','dataTable','dataTables-jqueryui','jqueryValidate',
			'bsButton','bsButtonEvent','bsMsgServ','formServ','bsUtil','codeDef','datagridServ'
			,'moment','bootstrap-datetimepicker','bootstrap-datetimepicker.zh-CN','dateUtil'],
    	function($,init,dataTable,ui,validate,
    				bsButton,bsButtonEvent,bsMsgServ,formServ,bsUtil,codeDef,datagridServ
    				,moment,datetimepicker,datetimepickerLang,dateUtil) {
		
    	//页面根节点
    	var rootid = 'issue-list',
    	
    	//脚本打开标志
    	isScriptOpen = false,
    	
    	//detail 按钮容器
    	detail_btn_container = rootid + ' .btn-container',
    	
    	//验证公用属性
    	ruleBase = {
    			errorElement : 'span',  
	            errorClass : 'js-required-field',  
	            focusInvalid : true
    	}
    	,
    	//当前业务字段验证规则
    	ruleConfig
    	,
    	//业务列表-表单容器对象
    	list_c = ' .list-detail',
    		
    	//当前业务模块代码
    	current_bizcode, 

    	//当前模块配置
    	current_config,
    	
    	//当前选中行
    	curent_selectRow,
    	
    	//字段配置url
    	field_url = '/flowTaskConfig/query/getTaskConfig.action'
    	
		var private_method = {
    	
    	/**
    	 * 初始化侧边栏导航
    	 */
    	initNav:function(){
    		var _param = {
    			url:'/'+init.getSite()+'/permission/query/getUserDutiesMenu.action',
    			success:function(data){
    				if(window.console){
    					console.log('menu data: ' + data.length);
    				}
    				var _el = $('#' + rootid + ' #left-nav')
    				if(_el.length==1){
    					//设定导航栏高度
    					var _navCss = {
    						"overflow"  : "auto",
    						"overflow-x": "hidden", 
    						"height"    : init.getGridHeight()+'px'} 
    					$(_el).css(_navCss);
    					
    					var _html = '';
    					$.each(data,function(i,o){
    						
    						_html+='<li>'+
    							   
    							   '<a class="left-nav-btn" href="javascript:void(0);" id="'+o.bizcode+'">'+ 
    							   '<span class="'+o.iconcls+'">' + o.pre_name +'</span>'+
    							   ' ' +o.short_name +
    							   '<span class="badge badge-'+ o.bizcode+'-notify-list"></span>'+
    							   '</a>'+
    							   '</li>'
    						
    					})
    					
    					if(_html){
    						_el.empty();
    						_el.append(_html);
    						
    						//绑定导航链接事件
    						private_method.btn_listenner();
    						
    						//绑定查询事件
    						private_method.bind_search_click();
    						
    						bsUtil.updateIssueBadge();
    					}
    				}
    			}
    		}
    		$.ajax(_param)
    	},
    	/**
    	 * 初始化列表
    	 * @param _options.module	模块代码
    	 * @param _options.ajax		server端数据访问方法
    	 * @param _options.paging	分页标志
    	 * @param _options.columns	缺省列
    	 */
    	initList:function(_options){
    		
    		
    		 var _param ={
    		 	height:init.getGridHeight(),
    		 	rownumbers:true,
				animate: true,									
				striped:true,
				border:true,
				//singleSelect:false,
				idField: 'id',
				treeField: 'name',					
				fitColumns: true,
				checkOnSelect:true,					
				selectOnCheck:true,
				pagination: true,
				queryParams: {bizcode:current_bizcode},
				url:'/'+init.getSite()+'/'+_options.module+'/query/getAllTaskListDomain.action',
				columns:[[
					{field:'ck',checkbox:true},
					{field:'bizno',title:'业务编码',width:50,halign:'center'},        
					{field:'name',title:'事项名称',width:100,halign:'center'},        
					{field:'apply_deptname',title:'申请科室',width:50,halign:'center'} ,
					{field:'apply_name',title:'申请人员',width:50,halign:'center'} ,
					{field:'apply_date',title:'申请时间',width:50,halign:'center'},
					{field:'flowState',title:'事项状态',width:50,halign:'center'} 
//					{field:'apply_name',title:'操作',width:50,align:'center',
//						formatter:function(value,row,index){
//							return  '<span><font color=blue>下载</font></span>';
//						}
//					}
					
				]],
				onDblClickRow:private_method.dblClick
    		 }
    		 
    		 var queryParam = private_method.getSercehValue();
    		 if(queryParam){
    		 	_param.queryParams = $.extend({},_param.queryParams,queryParam);    		 	
    		 }
    		 var dg = $('#' + rootid + ' .dg-list')
    		 if(dg.length>0){
    		 	dg.datagrid(_param)
    		 }
    		 
    		 //初始化时间字段
    		 private_method.initDatepicker();
    		
    	}
    	
    	,
			initDatepicker:function(){
				
				var _start = $('#'+rootid + ' .search-form #apply_date_start')
				var _end = $('#'+rootid + ' .search-form #apply_date_end')
				
				var _param ={
					language:  'zh-CN',
					format: "yyyy-mm-dd",
					autoclose: true,
					minView: "month",
					maxView: "decade",
					todayBtn: true,
					pickerPosition: "bottom-left"
				}
				
				if(_start.length==1){
					
					_start.datetimepicker(_param);
					
					if(_end.length==1){
						
						_start.on("click",function(ev){
							_start.datetimepicker("setEndDate", _end.val());
						})
						
						_end.datetimepicker(_param)
							.on("click", function (ev) {
								_end.datetimepicker("setStartDate", _start.val());
							})
					}
				}				
			}
    	,
    	/**
    	 * 双击事件
    	 */
    	dblClick:function(index,data){    		
    		
    		var dg = $('#' + rootid + ' .dg-list')
    		dg.datagrid('clearSelections');
    		dg.datagrid('selectRow',index);
    		var _btn = $('#' + rootid + ' [btn-type="listViewReplace"]');
    		_btn.trigger('click');
    		
    	}
    	,
    	/**
    	 * 初始化
    	 */
    	initEdit:function(_options){
    		
    		//清理遗留数据
    		
    		//绑定按钮事件，redraw函数完成
    		
    		
    		
    		//判断是否存在自定义初始化函数
    		if(_options.initElement){
    			_options.initElement();	
    		}
    		
    		//获取字段验证规则,显示必填项
    		private_method.getFieldConfig();
    		
    		//初始化表单元素
    		private_method.initForm();
    		
    		//初始化部门、人员及时间信息
    		private_method.initDeptUser();
    	}
    	,
    	/**
    	 * 按钮事件定义
    	 */
    	btn_listenner:function(){
    		var _btn = $('#'+rootid +' a.left-nav-btn')
    		if(_btn.length>0){
    			_btn.unbind('click');
    			_btn.bind('click',private_method.navClick)
    		}
    	}
    	,
    	
    	initDeptUser:function(){
    		var usr = init.getCurrentUser();
					
			if(usr){
				//初始化部门信息
				var _elid = $('#'+rootid + ' .main-form #apply_deptid')
				var _elname = $('#'+rootid + ' .main-form #apply_deptname')
				var _val
				if(_elname.length==1){
					_val = _elname.val();
					if(!_val){
						_elname.val(usr.deptName);
						_elid.val(usr.deptid);
					}
				}
				
				//初始化人员信息
				_elid = $('#'+rootid + ' .main-form #apply_id')
				_elname = $('#'+rootid + ' .main-form #apply_name')
				var _val
				if(_elname.length==1){
					_val = _elname.val();
					if(!_val){
						_elname.val(usr.name);
						_elid.val(usr.id);
					}
				}
				
				//初始化时间
				var _elDate = $('#'+rootid + ' .main-form #apply_date')
				
				var _param ={
						language:  'zh-CN',
						format: "yyyy-mm-dd hh:ii:ss",
						autoclose: true,
						minView: "month",
						maxView: "decade",
						todayBtn: true,
						pickerPosition: "bottom-left"
					}
				_elDate.datetimepicker(_param);
				var _elVal
				if(_elDate.length==1){
					_elVal = _elDate.val();
					if(!_elVal){
						_elDate.val(dateUtil.getDateValue({format:'yyyy-MM-dd hh:mi:ss'}))	
					}
				}
				
			}
    	}
    	,
    	/**
    	 * 业务类型点击事件
    	 */
    	navClick:function(e){
    		
    		//选中状态 class 调整
    		$('#' + rootid + ' #left-nav li').removeClass('active');
    		$(e.currentTarget).closest('li').addClass('active');
    		
    		//获取选中对象类型
    		current_bizcode = init.getNavType(e);
    		if(window.console){
				console.log('module: ' + current_bizcode);
			}
    		
    		//获取容器对象
			var _c =$('#' + rootid +list_c)
    		
			//刷新容器对象，变更数据
			if(_c){
				//清除原有内容
				_c.empty();
				
				var _html = '<table class="dg-list" cellspacing="0" width="100%"></table>';
				_c.append(_html);
			}			
			
			private_method.redrawBtn({
				bizcode: current_bizcode,
    			btnType: 'listView',
				container: detail_btn_container
			})
    		private_method.initList({module:current_bizcode});
    	}
    	,
    	
    	clearDetail:function(){
    		var _c =$('#' + rootid +list_c)
    			
    			if(_c){
    				//清除原有内容
    				_c.empty();
    			}
    	}
    	
    	,
    	
    	/**
    	 * 更新按钮
    	 * @param _options.bizcode	业务编码
    	 * @param _options.btnType		按钮类型(list,edit,view)
    	 * @param _options.bizType	业务类型(0:normal,1:flow,2:audit)
    	 * @param _options.container 按钮容器对象
    	 */
    	redrawBtn:function(_options){
    		
    		
    		var _btn ;
    		if(_options && _options.btnType){    			
	    		_btn = bsButton.getBtn(_options);	    				
    		}    		
    		
    		$('#'+_options.container).empty();
    		
    		if(_btn){    			
    			$('#'+_options.container + ' button').unbind('click');    			
    			$('#'+_options.container).append(_btn);    			
    			//绑定按钮事件
    			$('#'+_options.container + ' button').bind('click',private_method.btnClick);
    		}
    		
    	}
    	,
    	
    	
    	
    	reDrawBizBadge:function(){
    		var _el = $('#'+rootid + ' .active span')
    		
    		var grid = $('#'+rootid + ' .dg-list')
    		
    		var _o = grid.datagrid('options')
    		var _cnt = _o.total
    		_el.html(_cnt);
    		
    	}
    	,
    	btnClick:function(e){
    		
    		init.applyBtnEvt({btnEvt:e,btnConfig:btnEvent})
//    		bsMsgServ.msgSlide();
    	}
    
    	
    	

    	,
    	/**
    	 * 初始化表单页面元素
    	 * 	@param _options.rootid	dom根节点id
    	 * 
    	 */
    	initForm:function(_options){
    		
    		if(curent_selectRow){
    			
    			
    			var _el = $('#'+rootid + list_c + ' .main-form .money-control')
    			var _f = $('#'+rootid + list_c + ' .main-form')
    			
    			if(_options && _options.rootid){
    				_el = $('#'+_options.rootid + ' .main-form .money-control')
    				_f = $('#'+_options.rootid + ' .main-form')
    			}
    			
    			//清除金额字段验证函数
	    		if(_el.length>0){
	    			_el.removeClass('money-control');	    			
	    		}    			
    			
    			_f.form('load',curent_selectRow);    			
    		}
    		
    	}
    	
    	,
		/**
		 * 获取字段必填、可填配置
		 * 
		 */
		getFieldConfig:function(){
			//查询获取模块节点配置			
			var task_config_url = '/'+init.getSite() + field_url;
			var task_param = {}
			
			current_config = init.getBizConfig({bizcode:current_bizcode})
			if(current_config && current_config.fullBizcode){
				task_param.fullBizcode = current_config.fullBizcode;
			}
			
			//当前是否选中行
			if(curent_selectRow && curent_selectRow.task_def_key){
				task_param.activityId=curent_selectRow.task_def_key
			}
			
			$.ajax({
				url:task_config_url,
				data:task_param,
				type : 'post',
				success:private_method.fieldSetting
			})
		}
		
		,
		/**
		 * 设置form字段
		 */
		fieldSetting:function(data){
			if(data){
						

				var _f = data.editFilter

				var fields

				if(_f && _f.enabled){
					//旧模块流程定义配置模式
					fields = _f.enabled.split(',')
				}else{
					//新模块流程定义配置模式
					if(data.requiredFilter){
					fields = data.requiredFilter.split(',')
					}
				}

				if(fields && (fields.length>0)){
					var rules={},messages={}
					for(var i =0;i<fields.length;i++){
						var _el =$('#' + rootid + ' .main-form #' + fields[i])
						if(_el.length>0){
							 $(_el).addClass('js-required-field')
							 rules[fields[i]]='required';
							 messages[fields[i]]='字段不允许为空';
						}
					}
					ruleConfig = {rules:rules,messages:messages}
//					$($form).form('enableValidation').form('validate')
				}
			}
		}
		,
		validateForm:function(e){
			
			var _f = $('#'+rootid + ' .main-form')
			if(
				!formServ.validateForm({
					form:_f,
					rules:ruleConfig
				})
			){
				bsMsgServ.errorSlide('请填写表单内容');
				//释放按钮禁用状态
				$(e.currentTarget).removeClass('disabled');
				return 0
			}			
			
			return 1
		}
		,
		//获取form数据
		getFormData:function(){
			var _f = $('#'+rootid + ' .main-form')
			var formData = formServ.getDataObj({
						form : _f
					});
			//流程信息
//			if(current_config && current_config.flowid){
//				formData.flowid = current_config.flowid
//				formData.fullBizcode = current_config.fullBizcode
//			}
			
			//业务编码
//			if(!formData.bizcode){
//				var _bizcode = current_config.bizcode
//				formData.bizcode = _bizcode
//			}
			return formData;
		}
		,
		triggerNav:function(){
			var _btn = $('#' + rootid + ' .active a')
    		_btn.trigger('click');	
			
		}
		,
		bind_search_click:function(){
			var _btn = $('#'+rootid + ' button[btn-type=search]')
			if(_btn.length>0){
				_btn.unbind('click');
				_btn.bind('click',btnEvent.search);
			}
		}
		
		,
		//获取查询参数
		getSercehValue:function(){
			var _el = $('#'+rootid + ' .search-form #name');
			
			//模糊查询字段定义
			var fuzzy = {};
			//模糊查询字段内容
			if(_el.length==1){
				var _name = _el.val();
				if(_name){
					var _fuzzy ={														
							fuzzy:{name_like:_name,
							apply_deptname_like:_name,
							apply_name_like:_name,
							bizno_like:_name}
						}
					fuzzy = _fuzzy;
				}				
			}
			
			//获取时间字段值
			var _els = $('#'+rootid + ' .search-form #apply_date_start');
			var _ele = $('#'+rootid + ' .search-form #apply_date_end');
			var _vs = _els.val();
			var _ve = _ele.val();
			
			
			//业务编码
			var condition = {};
			if(current_bizcode){
				condition.module=current_bizcode
			}
			
			var _da = ' 00:00:00';
			//时间起始值
			if(_vs){
				//起始时间有值
//				_vs = _vs + _da;
				if(_ve){
				//结束时间有值
//					_ve = _ve + _da;
					condition = {condition:{apply_date_start:_vs,apply_date_end:_ve}}									
				}else{
					//结束时间未输入值
					condition = {condition:{apply_date:_vs}}
				}			
			}else{
				//起始时间无值
				if(_ve){
					//结束时间有值
//					_ve = _ve + _da;
					condition = {condition:{apply_date:_ve}}
				}
			}
			return $.extend({},condition,fuzzy)
		}
		
	};
	
	var btnEvent = {
		
		 	
    	
    	//当前页编辑
    	listViewReplace:function(e){
    		var _record = $('#' + rootid + ' .dg-list').datagrid('getSelections');
    		
    		if(_record.length==1){
	    		var _url = '/common/query/getBizPage.action?subSystem=oa&code=bsEditDlg&module='+current_bizcode
	    		bsButtonEvent.add({
	    			url:_url,
	    			container:'issue-list .list-detail',
	    			formInit:null,
	    			data:_record,
	    			evt:e
	    		})	 
	    			    		
	    		//暂存当前选中行
	    		curent_selectRow = _record[0];
	    		
	    		//刷新按钮
	    		private_method.redrawBtn({
					bizcode: current_bizcode,
	    			btnType: 'view',
					container: detail_btn_container
				})
    		}else{
    			if(_record.length>1){
    				bsMsgServ.warnSlide('您选择了多条记录，请鼠标双击想编辑的行.')	
    			}else{
    				bsMsgServ.warnSlide('请选择想操作的行')	
    			}
    			$(e.currentTarget).removeClass('disabled');
    		}
    		
    		
    	}
    	
    	,
    	//取消编辑
    	editCancelReplace:function(){
    		
    		private_method.triggerNav();
    	}
    	,
    	//导出excel
    	exportExcel:function(e){
    		var _url = '/'+init.getSite()+'/'+current_bizcode+'/query/exportExcel.action';
    		var _param = {};
    		bsButtonEvent.exportAll({url:_url,queryParam:_param});
    		$(e.currentTarget).removeClass('disabled');
    	}
    	
    	,
    	//导出审批完成的excel
    	exFinished:function(e){
    		var _url = '/'+init.getSite()+'/'+current_bizcode+'/query/exportExcelFinished.action';
    		var _param = private_method.getSercehValue();
    		bsButtonEvent.exportAll({url:_url,queryParam:_param});
    		$(e.currentTarget).removeClass('disabled');
    	}
    	,
    	search:function(e){
			//获取文档明细列表		
			var _param = private_method.getSercehValue();			
			
			var dg = $('#' + rootid + ' .dg-list')
			if(dg.length==1){
				dg.datagrid('load',_param)	
			}
		}
    	,
		/**
		 * 导出word
		 * 
		 */
		editExportWord:function(e){			
					
			var _id = $('#'+rootid + ' .main-form #id').val();
			
			if(_id){
				var _url = '/'+init.getSite() +'/'+ current_bizcode +'/query/exportWord.action';
				var form = $("<form>");
				form.attr('style','display:none');
				form.attr('target','');
				form.attr('method','post');
				form.attr('accept-charset','utf-8');
				form.attr('action',_url);
				var input1 = $("<input>");
				input1.attr('type','hidden')
				input1.attr('name','id')
				input1.attr('value',_id);
				$('body').append(form);
				$(form).append(input1);
				
				form.submit();
				form.remove();
			}
			$(e.currentTarget).removeClass('disabled');
		}
	}
	
	var public_method = {
		initList:function(){
			rootid = 'issue-list'
			isScriptOpen = false;
			private_method.initNav();
		}
		,
		/**
		 * 初始化编辑页面
		 */
		initEdit:function(_options){
			
			private_method.initEdit(_options)
		}
		,
		/**
		 * @param _options.rootid	dom根节点id
		 */
		initForm:function(_options){
			
			private_method.initForm(_options);	
		}
		,
		/**
		 * @param _options.rootid	dom根节点id
		 * @param _options.flowInstId		流转业务对象唯一id
		 * @param _options.bizcode	流转对象业务代码
		 */
		openViewPage:function(_options){
			
			if(_options && _options.rootid && _options.flowInstId && _options.bizcode){
				isScriptOpen = true;
				rootid = _options.rootid;
				current_bizcode = _options.bizcode;
				
				bsUtil.getflowData({
					flowInstId	: _options.flowInstId,
					bizcode		: _options.bizcode,
					callback	: function(data){
						curent_selectRow = data;
					}
				})
			}
		}
		,
		getCurrentBizcode:function(){
			return current_bizcode;	
		}
		
	}
	
	return public_method;
		
    
})
